#include <dao/UserDao.h>
#include <dao/MySQLConnPool.h>
#include <cppwinks/utility/format/Format.h>
#include <iostream>

using namespace std;
using namespace mysql;
using namespace format;

UserDao *user_dao = new UserDao;

// 插入用户
bool UserDao::insertUser(const std::string &n, const std::string &p, const std::string &ph, const std::string &g)
{
    shared_ptr<MysqlPreparedStatement> stmt = pool->getConnection()->prepareStatement("INSERT INTO `users`(`username`,`password`,`phone`,`gender`) VALUES(?,?,?,?)");
    stmt->setString(1, n);
    stmt->setString(2, p);
    stmt->setString(3, ph);
    stmt->setString(4, g);
    return stmt->execute();
}

// 删除用户
void UserDao::deleteUserById(int id)
{
    try
    {
        shared_ptr<MysqlPreparedStatement> stmt = pool->getConnection()->prepareStatement("DELETE FROM user WHERE id =?");
        stmt->setInt(1, id);
        stmt->execute();
    }
    catch (const std::exception &e)
    {
        std::cerr << "删除用户记录时出现数据库异常" << '\n';
    }
}

// 登录
int UserDao::validateLogin(const std::string &username, const std::string &password)
{
    std::shared_ptr<MysqlPreparedStatement>
    stmt = pool->getConnection()->prepareStatement("SELECT id FROM users WHERE username= ? AND password = ?");
    stmt->setString(1, username);
    stmt->setString(2, password);
    mysql::MysqlResult resultSet = stmt->executeQuery();
    return resultSet.getRowCount() > 0?resultSet.next(),resultSet.getInt(0): -1;
}
void UserDao::updateUser(int id, const std::string &username, const std::string &password, const std::string &phone, const std::string &gender)
{
    try
    {
        shared_ptr<MysqlPreparedStatement> stmt = pool->getConnection()->prepareStatement("UPDATE user SET username=?,password=?,phone=?,gender=? WHERE id=?");
        stmt->setString(1, username);
        stmt->setString(2, password);
        stmt->setString(3, phone);
        stmt->setString(4, gender);
        stmt->setInt(5, id);
    }
    catch (const std::exception &e)
    {
        std::cerr << "异常情况: " << e.what() << std::endl;
    }
}
